#include "RateMonitor.h"

RateMonitor::RateMonitor() = default;
RateMonitor::~RateMonitor()
{
    stop();
}

void RateMonitor::start()
{
    running_ = true;
    thread_ = std::thread(&RateMonitor::run, this);
}

void RateMonitor::stop()
{
    running_ = false;
    if (thread_.joinable())
    {
        thread_.join();
    }
}

void RateMonitor::incRecv()
{
    recvCounter_.fetch_add(1, std::memory_order_relaxed);
}

void RateMonitor::incSend()
{
    sendCounter_.fetch_add(1, std::memory_order_relaxed);
}

void RateMonitor::setCallback(Callback cb)
{
    callback_ = std::move(cb);
}

void RateMonitor::run()
{
    while (running_)
    {
        auto start = std::chrono::steady_clock::now();
        std::this_thread::sleep_for(std::chrono::seconds(1));
        auto end = std::chrono::steady_clock::now();

        uint64_t recv = recvCounter_.exchange(0, std::memory_order_relaxed);
        uint64_t send = sendCounter_.exchange(0, std::memory_order_relaxed);

        if (callback_)
        {
            callback_(recv, send);
        }
        else
        {
            std::cout << "[RateMonitor] RecvRate: " << recv << " pkt/s, SendRate: " << send << " pkt/s" << std::endl;
        }
    }
}
